//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package chat_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MemberDbItem struct {
	MemberId    string `bson:"_id"` //自动生成
	ProjectId   string `bson:"projectId"`
	ChatGroupId string `bson:"chatGroupId"`
	UserId      string `bson:"userId"`
	UnreadCount uint32 `bson:"unreadCount"`
	LastMsgTime int64  `bson:"lastMsgTime"`
	JoinTime    int64  `bson:"joinTime"`
}

type _GroupMemberDao struct {
	mc *mongo.Collection
}

func newGroupMemberDao(db *mongo.Database) (*_GroupMemberDao, error) {
	mc := db.Collection(db_ns.DB_NS_CHAT + "group_member")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"projectId", 1}, {"chatGroupId", 1}},
		},
		{
			Keys: bson.D{{"projectId", 1}, {"userId", 1}, {"lastMsgTime", -1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_GroupMemberDao{mc: mc}, nil
}

func (db *_GroupMemberDao) Insert(ctx context.Context, dbItem *MemberDbItem) error {
	dbItem.MemberId = db.genMemberId(dbItem.ChatGroupId, dbItem.UserId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_GroupMemberDao) genMemberId(chatGroupId, userId string) string {
	return fmt.Sprintf("%s:%s", chatGroupId, userId)
}

func (db *_GroupMemberDao) Exist(ctx context.Context, projectId, chatGroupId, userId string) (bool, error) {
	memberId := db.genMemberId(chatGroupId, userId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": memberId, "projectId": projectId})
	return count > 0, err
}

func (db *_GroupMemberDao) Get(ctx context.Context, projectId, chatGroupId, userId string) (*MemberDbItem, error) {
	memberId := db.genMemberId(chatGroupId, userId)
	retItem := &MemberDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": memberId, "projectId": projectId}).Decode(retItem)
	if err != nil {
		return nil, err
	}
	return retItem, nil
}

func (db *_GroupMemberDao) Remove(ctx context.Context, projectId, chatGroupId, userId string) error {
	memberId := db.genMemberId(chatGroupId, userId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": memberId, "projectId": projectId})
	return err
}

func (db *_GroupMemberDao) RemoveByUser(ctx context.Context, projectId, userId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"projectId": projectId, "userId": userId})
	return err
}

func (db *_GroupMemberDao) RemoveByChatGroup(ctx context.Context, projectId, chatGroupId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"projectId": projectId, "chatGroupId": chatGroupId})
	return err
}

// 列出聊天组内的成员
func (db *_GroupMemberDao) ListMember(ctx context.Context, projectId, chatGroupId string) ([]*MemberDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "chatGroupId": chatGroupId}, options.Find().SetSort(bson.M{"joinTime": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*MemberDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_GroupMemberDao) ListMemberByGroupList(ctx context.Context, projectId string, chatGroupIdList []string) ([]*MemberDbItem, error) {
	if len(chatGroupIdList) == 0 {
		return []*MemberDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "chatGroupId": bson.M{"$in": chatGroupIdList}}, options.Find().SetSort(bson.M{"joinTime": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*MemberDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

// 列出聊天组
func (db *_GroupMemberDao) ListChatGroup(ctx context.Context, projectId, userId, skipChatGroupId string) ([]*MemberDbItem, error) {
	query := bson.M{"projectId": projectId, "userId": userId}
	if skipChatGroupId != "" {
		query["chatGroupId"] = bson.M{"$ne": skipChatGroupId}
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSort(bson.M{"lastMsgTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*MemberDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_GroupMemberDao) IncUnreadCount(ctx context.Context, projectId, chatGroupId string) error {
	_, err := db.mc.UpdateMany(ctx, bson.M{"projectId": projectId, "chatGroupId": chatGroupId}, bson.M{"$inc": bson.M{"unreadCount": 1}})
	return err
}

func (db *_GroupMemberDao) UpdateLastMsgTime(ctx context.Context, projectId, chatGroupId string, lastMsgTime int64) error {
	_, err := db.mc.UpdateMany(ctx, bson.M{"projectId": projectId, "chatGroupId": chatGroupId}, bson.M{"$set": bson.M{"lastMsgTime": lastMsgTime}})
	return err
}

func (db *_GroupMemberDao) ClearUnreadCount(ctx context.Context, projectId, chatGroupId, userId string) error {
	memberId := db.genMemberId(chatGroupId, userId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": memberId, "projectId": projectId}, bson.M{"$set": bson.M{"unreadCount": 0}})
	return err
}
